<template>
  <div>
    <div class="prompt">
      <p>温馨提示：</p>
      为保证能够正确导入数据，导入模板数据需与配置状态一致。
    </div>
    <div class="time">
      <div class="tit">
        <div></div>
        数据导入月份
      </div>
      <a-month-picker
        v-model="time"
        placeholder="选择月份"
        :allow-clear="false"
        style="width: 338px;margin-top:12px;"
        @change="monthChange"
      />
    </div>
    <div class="xq-form-wrapper" style="padding: 0 24px">
      <a-row style="margin-bottom: 24px;" type="flex" align="middle" justify="space-between">
        <a-col :span="12">
          <div class="tit">
            <div></div>
            模板配置
          </div>
        </a-col>
        <a-col>
          <a-button style="margin-right:18px;" @click="onAdd">
            新增配置项
          </a-button>
          <a-button type="primary" @click="download">
            下载模板
          </a-button>
        </a-col>
      </a-row>
      <a-spin :spinning="spinning" class="xq-form-content">
        <XqTable
          :customize="FormJson['config']['table']['customize']"
          :scroll="{ x: columns.length * 150 }"
          :pagination="false"
          :dataSource="tableData"
          :columns="columns"
          class="xq-form-content-table"
        >
          <template v-for="(col, index) in columns" v-slot:[`xq_${col.dataIndex}`]>
            <span :key="index">
              {{ col.customTitle }}
            </span>
          </template>
          <!-- eslint-disable-next-line prettier/prettier -->
          <template v-for="(col, index) in columns" v-slot:[col.dataIndex]="text, record">
            <!-- <span v-if="col.dataIndex === 'gmtCreate'" :key="index">
              {{ moment(text).format("YYYY/MM/DD") }}
            </span> -->
            <span v-if="col.dataIndex === 'configurationExplain'" :key="index">
              <span>{{ text || "--" }}</span>
            </span>
            <span v-else-if="col.dataIndex === 'tableAction'" :key="index">
              <a @click="onMsg(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm :title="`确认要删除吗？`" ok-text="确认" cancel-text="取消" @confirm="onDel(record.id)">
                <a :disabled="record.isSystemConfigure">删除</a>
              </a-popconfirm>
            </span>
            <XqTableCell v-else :key="index" :record="record" :field="FormJson['fields'][col.dataIndex]" :dynamicData="dynamicData" />
          </template>
        </XqTable>
        <div class="xq-form-content-pagination">
          <div class="xq-form-content-pagination-total">共 {{ total }} 条</div>
          <a-pagination
            v-model="pageNo"
            :page-size="pageSize"
            :total="total"
            :show-size-changer="true"
            :show-quick-jumper="true"
            :page-size-options="['10', '20', '50', '100']"
            @change="onPageChange"
            @showSizeChange="onPageSizeChange"
          />
        </div>
      </a-spin>
    </div>
    <div class="set-btn">
      <a-button :disabled="!time" type="primary" @click="$emit('onAction', 1, uploadJson)">
        上传考勤表
      </a-button>
    </div>
    <drawer
      :id="id"
      :attendanceSallaryTemplateId="attendanceSallaryTemplateId"
      :name="configurationName"
      :visible.sync="visible"
      @upDate="onUpDate"
    />
  </div>
</template>

<script>
import axios from "axios";
import qs from "qs";
import FormJson from "./FormJson";
import XqCurdMixin from "xqjr-plugin-form/mixins/XqCurdMixin";
import { getAttendanceSallaryTemplateInfo, delAttendanceSallaryTemplateItems } from "../../api";
import drawer from "./component/drawer";
import moment from "moment";

const curdMixin = new XqCurdMixin({
  FormJson,
  tableConfigKey: "table"
});

export default {
  mixins: [curdMixin],
  components: { drawer },
  data() {
    return {
      time: "",
      uploadJson: {},
      spinning: false,
      tableData: [],
      total: 0,
      pageNo: 1,
      pageSize: 20,
      visible: false,
      id: "",
      attendanceSallaryTemplateId: "",
      configurationName: ""
    };
  },
  created() {
    this.onGetAttendanceSallaryTemplateInfo();
  },
  methods: {
    moment,
    async onGetAttendanceSallaryTemplateInfo() {
      try {
        this.spinning = true;
        const { data } = await getAttendanceSallaryTemplateInfo({
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          companyId: this.$store.state.hr.companyId
        });
        this.tableData = data.entities;
        this.total = data.entityCount;
        this.attendanceSallaryTemplateId = this.tableData[0].attendanceSallaryTemplateId;
        setTimeout(() => (this.spinning = false), 500);
      } catch (err) {
        console.log("error log --> ", err);
        setTimeout(() => (this.spinning = false), 500);
      }
    },
    onPageChange(page) {
      this.pageNo = page;
      this.onGetAttendanceSallaryTemplateInfo();
    },
    onPageSizeChange(current, pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.onGetAttendanceSallaryTemplateInfo();
    },
    async onDel(id) {
      try {
        await delAttendanceSallaryTemplateItems(id);
        if (this.tableData.length === 1) {
          this.pageNo > 1 ? (this.pageNo = this.pageNo - 1) : (this.pageNo = 1);
        }
        this.onGetAttendanceSallaryTemplateInfo();
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onSearch() {
      this.pageNo = 1;
      this.onGetAttendanceSallaryTemplateInfo();
    },
    onAdd() {
      this.visible = true;
    },
    onMsg(e) {
      this.id = e.id;
      this.configurationName = e.configurationName;
      this.visible = true;
    },
    onUpDate(e) {
      this.id = "";
      this.configurationName = "";
      if (e) this.onGetAttendanceSallaryTemplateInfo();
    },
    monthChange(date, dateString) {
      this.time = moment(dateString).format("YYYY-MM");
      this.uploadJson = {
        type: "upload",
        year: moment(dateString).format("YYYY"),
        month: moment(dateString).format("MM"),
        tempId: this.attendanceSallaryTemplateId
      };
    },
    download() {
      const token = this.$store.state.auth.token;
      let params = {};
      params = {
        // templateName: "allEmployeeSalary.xlsx"
      };
      axios({
        url: `/hr/api/v1/attendanceSallaryTemplateItems/downloadAttendanceSallaryTemplate/${this.attendanceSallaryTemplateId}`,
        params,
        paramsSerializer: param => {
          return qs.stringify(param, { indices: false });
        },
        method: "GET",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", "考勤工资模板.xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          console.log("error log --> ", err);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.set-btn {
  width: 100%;
  height: 40px;
  line-height: 62px;
  text-align: center;
  border-top: 1px solid #e8e8e8;
  margin-top: 24px;
}

.prompt {
  width: calc(100% - 48px);
  height: 84px;
  border-bottom: 1px solid #e8e8e8;
  margin: 20px 24px 24px 24px;
  font-size: 14px;
  line-height: 26px;
  p {
    font-size: 16px;
    font-weight: 400;
    margin-bottom: 14px;
    color: #252525;
  }
}

.time {
  padding: 0 24px;
  margin: 24px 0 30px 0;
}

.tit {
  font-size: 16px;
  line-height: 20px;
  div {
    display: inline-block;
    width: 3px;
    height: 20px;
    background: #6a66f6;
    border-radius: 2px;
    vertical-align: bottom;
    margin-right: 10px;
  }
}
</style>
